<template>
  <el-dialog
    :title="dialogTitle"
    :visible="showDialog"
    :close-on-click-modal="false"
    @close="handleCloseDialog"
    @open="getSimpleUserList"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-10个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-10个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="clickSubmit"
        >确定</el-button
      >
      <el-button size="small" @click="handleCloseDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
// code	string	非必须		部门编码，同级部门不可重复
// introduce	string	非必须		介绍
// manager	string	非必须		负责人名称
// name	string	非必须		部门名称
// pid	string	非必须		父级部门ID
import { reqGetSimpleUserList } from "@/api/user";
import {
  reqAddDepartment,
  reqGetDepartDetail,
  reqUpdateDepartDetail,
} from "@/api/departments";
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    nodeData: {
      type: Object,
      required: true,
    },
    deptsList: {
      type: Array,
      required: true,
    },
  },
  data() {
    //   自定义校验部门名称
    const validateName = (rules, value, callback) => {
      console.log(value, this.nodeData.id, this.deptsList);
      let res = [];
      if (this.form.id) {
        if(this.nodeData.name === value){
          callback()
          return 
        }
        res = this.deptsList.filter((item) => item.pid === this.nodeData.pid);
      } else {
        res = this.deptsList.filter((item) => item.pid === this.nodeData.id);
      }
      const isReapt = res.some((item) => item.name === value);
      // if(isReapt){
      //     callback(new Error('同级部门已经出现该部门名称'))
      // }else{
      //     callback()
      // }
      isReapt ? callback(new Error("同级部门已经出现该部门名称")) : callback();
    };
    // 自定义校验部门编码
    const validateCode = (rules, value, callback) => {
      console.log(value);
      if (this.form.id && value === this.nodeData.code) {
        callback();
        return;
      }
      const isReapt = this.deptsList.some((item) => item.code === value);
      isReapt ? callback(new Error("该部门编码已经被占用了")) : callback();
    };
    return {
      dialogTitle: "标题",
      userList: [],
      form: {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "部门名称不能为空",
            trigger: ["blur", "change"],
          },
          {
            min: 1,
            max: 10,
            message: "部门名称只能是1-10个字符",
            trigger: ["blur", "change"],
          },
          { validator: validateName, trigger: "blur" },
        ],
        code: [
          {
            required: true,
            message: "部门编码不能为空",
            trigger: ["blur", "change"],
          },
          {
            min: 1,
            max: 10,
            message: "部门编码只能是1-10个字符",
            trigger: ["blur", "change"],
          },
          { validator: validateCode, trigger: "blur" },
        ],
        manager: [
          {
            required: true,
            message: "部门名称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        introduce: [
          {
            required: true,
            message: "部门介绍不能为空",
            trigger: ["blur", "change"],
          },
          {
            min: 1,
            max: 300,
            message: "部门介绍只能是1-300个字符",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    // handleCloseDialog() {
    //   this.$emit("close-dialog", false);
    // },
    handleCloseDialog() {
      this.$emit("update:showDialog", false);
      this.$refs.form.resetFields();
    },
    async getSimpleUserList() {
      const { data } = await reqGetSimpleUserList();
      this.userList = data;
      console.log(this.userList);
    },
    clickSubmit() {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return;
        console.log("已经通过，可以发请求了");

        if (this.form.id) {
          // 编辑
          const res = await reqUpdateDepartDetail(this.form);
          console.log(res);
          this.$message.success("编辑部门成功");
        } else {
          // 新增
          const res = await reqAddDepartment({
            ...this.form,
            pid: this.nodeData.id,
          });
          console.log(res);
          this.$message.success("新增部门成功");
        }
        // 关闭对话框
        this.handleCloseDialog();
        this.$emit("addDepts");
      });
    },
    async getDepartDetail() {
      const { data } = await reqGetDepartDetail(this.nodeData.id);
      this.form = data;
    },
  },
};
</script>

<style>
</style>